package com.sktlab.bizconfmobile.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sktlab.bizconfmobile.R;
import com.sktlab.bizconfmobile.customview.SlipControlView;
import com.sktlab.bizconfmobile.fragment.HomeFragment;
import com.sktlab.bizconfmobile.model.ConferenceAccount;
import com.sktlab.bizconfmobile.model.Constant;
import com.sktlab.bizconfmobile.model.db.AccountsDBAdapter;
import com.sktlab.bizconfmobile.model.db.AccountsDbTable;
import com.sktlab.bizconfmobile.model.manager.AccountsManager;
import com.sktlab.bizconfmobile.util.Util;
import com.sktlab.bizconfmobile.util.ValidatorUtil;


public class AddAccountActivity extends BaseActivity {
	
	public static final String TAG = "AddConfActivity";
	//add conference action
	public static final String ACTION_ADD_ACCOUNT = "com.sktlab.bizconfmobile.addconf.action";
	//edit conference action
	public static final String ACTION_EDIT_ACCOUNT = "com.sktlab.bizconfmobile.editconf.action";
	private Activity mCtx;
	private AccountsDBAdapter mAccountDb;
	
	private LinearLayout layoutConfCode;
	private LinearLayout layoutModeratorPw;
	
	private SlipControlView dialOutModule;
	private SlipControlView securityCodeModule;
	
	private RelativeLayout layoutAccessNumber;
	
	private EditText etAccountName;
	private TextView tvDialInNumber;
	private EditText etConfCode;
	private EditText etModeratorPw;
		
	private Button btConfirmAll;
	
	private final int MODE_RESET = 0; 
	//add account mode
	private final int MODE_ADD_ACCOUNT = 1; 
	//edit account mode
	private final int MODE_EDIT_ACCOUNT = 2; 
	
	private int operatorMode = MODE_RESET;
	
	private long editAccountId = -1L;
	//whether the access number is valid when DialOutEnable
	private boolean isAccessNumberValid = false;
	//whether the conference security code is valid when SecurityCodeEnable
	private boolean isSecurityCodeValid = false;
	
	private int mCurrentTab = -1;
	
	private OnClickListener dialOutModuleListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
			String phoneNum = dialOutModule.getInputContent();
			
			do{
				if(!ValidatorUtil.verifyPhoneNumber(mCtx, phoneNum)) {
					
					break;
				}
				
				//verify the phone number in server
				//...
				v.setEnabled(false);
				isAccessNumberValid = true;
			}while(false);
		}
	};
	
	private OnClickListener securityCodeModuleListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			String phoneNum = securityCodeModule.getInputContent();

			do {

				if (phoneNum == null || phoneNum.equalsIgnoreCase("")) {
	
					Util.shortToast(mCtx, R.string.toast_security_code_null);
					break;
				}
				
				//verify security code
				//...
				
				v.setEnabled(false);
				isSecurityCodeValid = true;
			} while (false);

		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_add_conf_account);
		
		mCtx = this;
		mAccountDb = new AccountsDBAdapter(AccountsDbTable.ACCOUNTS_DB_TABLE, 
				AccountsDbTable.getAllColumns());
		
		initView();		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		if(resultCode == RESULT_OK) {
						
			String accessNumber = data.getExtras().getString(AccessNumberActivity.KEY_ACCESS_NUMBER);
			
			if(Util.isEmpty(accessNumber)) {
				
				tvDialInNumber.setHint(R.string.access_number);
			}else {
				
				tvDialInNumber.setText(accessNumber);
			}
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}

	private boolean checkAllUserInput() {
		
		boolean isAllReady = false;
		
		do{
			if(Util.isEmpty(etAccountName.getText())){
				
				Util.shortToast(mCtx, R.string.toast_account_name_null);
				Util.requestFocus(etAccountName);
				break;
			}
			
			if(Util.isEmpty(tvDialInNumber.getText())){
				
				Util.shortToast(mCtx, R.string.toast_dial_in_num_null);
				Util.requestFocus(tvDialInNumber);
				break;
			}
			
			if(Util.isEmpty(etConfCode.getText())){
				
				Util.shortToast(mCtx, R.string.toast_conf_code_null);
				Util.requestFocus(etAccountName);
				break;
			}
			
			//when the user add normal account, the moderator password is not need
			if((mCurrentTab != HomeFragment.TAB_JOIN_CONF) && Util.isEmpty(etModeratorPw.getText())){
				
				Util.shortToast(mCtx, R.string.toast_moderator_pw_null);
				Util.requestFocus(etModeratorPw);
				break;
			}
					
			boolean isDialOutEnable = dialOutModule.getSlipState();
			
			if(isDialOutEnable && !isAccessNumberValid) {
				
				Util.shortToast(mCtx, R.string.toast_request_verify_dial_out_num);
				Util.requestFocus(dialOutModule.getInputView());
				break;
			}
			
			boolean isSecurityCodeEnable = securityCodeModule.getSlipState();
			
			if(isSecurityCodeEnable && !isSecurityCodeValid) {
				
				Util.shortToast(mCtx, R.string.toast_request_verify_security_code);
				Util.requestFocus(securityCodeModule.getInputView());
				break;
			}
			
			isAllReady = true;
			
		}while(false);
		
		return isAllReady;
	}
	
	private void initListener() {
		
		dialOutModule.setBtClickListener(dialOutModuleListener);
		securityCodeModule.setBtClickListener(securityCodeModuleListener);
		
		layoutAccessNumber.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				layoutAccessNumber.clearFocus();
				
				Intent intent = new Intent();
				intent.setClass(mCtx, AccessNumberActivity.class);

				mCtx.startActivityForResult(intent, 0);
			}
		});
		
		btConfirmAll.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				do{
					
					if(!checkAllUserInput()){
						
						break;
					}
					
					mAccountDb.open();
					
					ConferenceAccount account = generateAccount();
					
					switch (operatorMode) {

					case MODE_ADD_ACCOUNT:
						
						long accountId = mAccountDb.insertObject(account);
						account.setAccountId(accountId);
						
						boolean isAdded = AccountsManager.getInstance().addAccount(account);
						break;
						
					case MODE_EDIT_ACCOUNT:
						
						AccountsManager accountManager = AccountsManager.getInstance();
						
						ConferenceAccount rmAccount = accountManager.getAccountById(editAccountId);
						
						int index = accountManager.removeAccount(rmAccount);
						
						//because we have delete the old account which has a id corresponding to database _id,
						//so we should set the new account id as the old
						account.setAccountId(editAccountId);
						
						accountManager.addAccount(account,index);
						
						Util.BIZ_CONF_DEBUG(TAG, "edit dial out number" + account.getDialOutNumber());
						Util.BIZ_CONF_DEBUG(TAG, "editAccountId" + editAccountId);
						
						mAccountDb.updateObject(editAccountId, account);
						
						break;
						
					default:
						break;
					}
					
					mAccountDb.close();
					
					finish();							
				}while(false);
															
			}		
		});
	}
	
	private ConferenceAccount generateAccount() {
		
		ConferenceAccount account = new ConferenceAccount();
		
		account.setConfAccountName(etAccountName.getText().toString());
		account.setDialInNumber(tvDialInNumber.getText().toString());
		account.setConfCode(etConfCode.getText().toString());
		
		switch(mCurrentTab) {
		case HomeFragment.TAB_START_CONF:
		case HomeFragment.TAB_ORDER_CONF:
			//moderator account
			account.setModeratorPw(etModeratorPw.getText().toString());
			break;
		case HomeFragment.TAB_JOIN_CONF:
		default:
			//normal account
			account.setModeratorPw(AccountsDbTable.NORMAL_ACCOUNT_MODERATOR_PW);
			break;
		}		
				
		account.setDialOutEnable(dialOutModule.getSlipState());
		account.setSecurityCodeEnable(securityCodeModule.getSlipState());
		
		//when close dial out enable ,clear the value previous
		if(!dialOutModule.getSlipState()){
			dialOutModule.setInputContent("");
		}
		
		//when close security enable ,clear the value previous
		if(!securityCodeModule.getSlipState()){
			securityCodeModule.setInputContent("");
		}
		
		account.setDialOutNumber(dialOutModule.getInputContent());
		account.setSecurityCode(securityCodeModule.getInputContent());
		
		return account;
	}
	
	private void initView() {
		
		dialOutModule = (SlipControlView) findViewById(R.id.dial_out_module);
		securityCodeModule = (SlipControlView) findViewById(R.id.security_code_module);
		
		LinearLayout accountName = (LinearLayout) findViewById(R.id.etv_account_name);
		accountName.setBackgroundResource(R.drawable.input_top);
		
		TextView tvAccountName = (TextView) accountName.findViewById(R.id.tv_prompt);
		tvAccountName.setText(R.string.account_name);
		
		etAccountName = (EditText) accountName.findViewById(R.id.et_input);
		
		layoutAccessNumber = (RelativeLayout) findViewById(R.id.layout_access_number);
		tvDialInNumber = (TextView) layoutAccessNumber.findViewById(R.id.tv_center_content);
		
		layoutConfCode = (LinearLayout) findViewById(R.id.etv_conf_code);
		layoutConfCode.setBackgroundResource(R.drawable.input_center);
		
		TextView tvConfCode = (TextView) layoutConfCode.findViewById(R.id.tv_prompt);
		tvConfCode.setText(R.string.conf_code);
		
		etConfCode = (EditText) layoutConfCode.findViewById(R.id.et_input);
		etConfCode.setInputType(InputType.TYPE_CLASS_NUMBER);
		
		layoutModeratorPw = (LinearLayout) findViewById(R.id.etv_moderator_pw);
		layoutModeratorPw.setBackgroundResource(R.drawable.input_bottom);
		
		TextView tvMPw = (TextView) layoutModeratorPw.findViewById(R.id.tv_prompt);
		tvMPw.setText(R.string.moderator_pw);
		
		etModeratorPw = (EditText) layoutModeratorPw.findViewById(R.id.et_input);
		etModeratorPw.setInputType(InputType.TYPE_CLASS_NUMBER);
		btConfirmAll = (Button) findViewById(R.id.bt_confirm_all);
		
		initListener();
		
		do{
		
			Intent intent = getIntent();
			
			mCurrentTab = AppClass.getInstance().getCurrentTab();
			
			String action = intent.getAction();
			
			if(mCurrentTab == HomeFragment.TAB_JOIN_CONF){
				
				layoutModeratorPw.setVisibility(View.GONE);
				layoutConfCode.setBackgroundResource(R.drawable.input_bottom);
			}
			
			if(action.equalsIgnoreCase(ACTION_EDIT_ACCOUNT)) {
				
				operatorMode = MODE_EDIT_ACCOUNT;
				initEditContent();
				break;
			}
			
			if(action.equalsIgnoreCase(ACTION_ADD_ACCOUNT)) {
				
				operatorMode = MODE_ADD_ACCOUNT;									
				break;
			}
			
		}while(false);	
	}	
	
	private void initEditContent() {
		
		editAccountId = getIntent().getLongExtra(Constant.KEY_OF_CONF_ACCOUNT_ID, -1);
		
		ConferenceAccount account = AccountsManager.getInstance().getAccountById(editAccountId);
		
		if(!Util.isEmpty(account)){
			
			String accountName = account.getConfAccountName();
			String dialInNumber = account.getDialInNumber();
			String confCode = account.getConfCode();
			String moderatorPw = account.getModeratorPw();
			String dialOutNumber = account.getDialOutNumber();
			String securityCode = account.getSecurityCode();
			
			if(!Util.isEmpty(accountName)) {
				
				etAccountName.setText(accountName);
			}
			
			if(!Util.isEmpty(dialInNumber)) {
				
				tvDialInNumber.setText(dialInNumber);
			}
			
			if(!Util.isEmpty(confCode)) {
				
				etConfCode.setText(confCode);
			}
			
			if(!Util.isEmpty(moderatorPw)) {
				
				etModeratorPw.setText(moderatorPw);
			}
			
			if(account.isDialOutEnable() ){
				
				dialOutModule.setSlipState(true);
				
				dialOutModule.setInputContent(dialOutNumber);
			}
			
			if(account.isSecurityCodeEnable() ){
				
				securityCodeModule.setSlipState(true);
				
				if(!Util.isEmpty(securityCode)) {
					
					securityCodeModule.setInputContent(securityCode);
				}
				
			}
		}
	}
	
}
